package quantum2.math;

import java.math.BigDecimal;

public final class Arithmetic {

    private final double timeTol;

    private Arithmetic(double timeTol) {
        this.timeTol = timeTol;
        //this.timeTolBD = BigDecimal.valueOf(timeTol);
    }

    public Number zero() {
        return 0.0;
    }

    public Number add(Number n1, Number n2) {
        return n1.doubleValue() + n2.doubleValue();
    }

    public boolean isNear(Number n1, Number n2) {
        return Math.abs(n1.doubleValue() - n2.doubleValue()) < timeTol;
    }

    public Number evaluate(Number evalResult) {
        return evalResult.doubleValue();
    }

    private static final BigDecimal TWO = BigDecimal.valueOf(2);

    private static BigDecimal sqrt(BigDecimal a, int scale) {
        BigDecimal x0 = BigDecimal.ZERO;
        BigDecimal x1 = BigDecimal.valueOf(Math.sqrt(a.doubleValue()));

        while (!x0.equals(x1)) {
            x0 = x1;
            x1 = a.divide(x0, scale, BigDecimal.ROUND_HALF_UP);
            x1 = x1.add(x0);
            x1 = x1.divide(TWO, scale, BigDecimal.ROUND_HALF_UP);
        }

        return x1;
    }

    public Number sqrt(Number n) {
        return Math.sqrt(n.doubleValue());
    }

    public static Arithmetic createArithmetic(double timeTol) {
        return new Arithmetic(timeTol);
    }
}
